package global

import (
	"context"
	"fmt"
	"github.com/gomodule/redigo/redis"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go_init/cache"
	"go_init/config"
)

var (
	Config config.Config
	Mongo  *mongo.Client
	DB     *mongo.Database
	Redis  *cache.RedisPool
)


func initRedisPool() *cache.RedisPool {
	r := Config.Redis
	return &cache.RedisPool{
		Pool: redis.Pool{
			Dial: func() (redis.Conn, error) {
				return redis.Dial(r.Dial,
					fmt.Sprintf("%s:%s", r.Ip, r.Part),
					redis.DialPassword(r.Password),
					redis.DialDatabase(r.Database))
			},
			MaxIdle: r.MaxIdle,
			MaxActive: r.MaxActive,
		},
	}
}

func initMongoDB() (*mongo.Client, *mongo.Database) {
	m := Config.Mongodb
	clientOptions := options.Client().ApplyURI(m.Link())
	client, err := mongo.Connect(context.TODO(), clientOptions)
	if err != nil {
		panic("连接MongoDB失败")
	}
	err = client.Ping(context.TODO(), nil)
	if err != nil {
		panic("Ping => 测试连接失败")
	}
	return client, client.Database(m.Database)
}


func NewConfig() {
	Mongo, DB = initMongoDB()
	Redis = initRedisPool()
}